package com.zrf.gulimall.product.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zrf.gulimall.common.database.utils.PageUtils;
import com.zrf.gulimall.common.database.utils.Query;
import com.zrf.gulimall.product.dao.CategoryDao;
import com.zrf.gulimall.product.entity.CategoryBrandRelationEntity;
import com.zrf.gulimall.product.entity.CategoryEntity;
import com.zrf.gulimall.product.service.CategoryBrandRelationService;
import com.zrf.gulimall.product.service.CategoryService;
import com.zrf.gulimall.product.vo.web.Catelog2Vo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


@Service("categoryService")
@Slf4j
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

	@Resource
	private CategoryBrandRelationService categoryBrandRelationService;

	@Resource
	private RedissonClient redissonClient;

	@Resource
	private CacheManager cacheManager;

	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		IPage<CategoryEntity> page = this.page(
				new Query<CategoryEntity>().getPage(params),
				new QueryWrapper<CategoryEntity>()
		);

		return new PageUtils(page);
	}

	@Override
	public List<CategoryEntity> listWithTree() {
		// 1.查出所有分类
		List<CategoryEntity> entities = baseMapper.selectList(null);
		// 2.组装成树形结构
		return entities.stream()
				.filter(item -> item.getParentCid() == 0)
				.peek(item -> item.setChildren(getChildren(item, entities)))
				.sorted(Comparator.comparingInt(item -> item.getSort() == null ? 0 : item.getSort()))
				.collect(Collectors.toList());
	}

	@Override
	public List<CategoryEntity> queryByBrandId(Long brandId) {
		List<CategoryBrandRelationEntity> brandRelationEntities = categoryBrandRelationService.queryByBrandId(Collections.singletonList(brandId));
		List<Long> catalogIdList = brandRelationEntities.stream().map(CategoryBrandRelationEntity::getCatelogId).distinct().collect(Collectors.toList());
		if (CollUtil.isEmpty(catalogIdList)) {
			return null;
		}
		return this.listByIds(catalogIdList);
	}

	@Override
	public void removeMenuByIds(List<Long> asList) {
		// 过滤被引用的菜单
		List<CategoryBrandRelationEntity> categoryBrandRelationEntities = categoryBrandRelationService.queryByCatalogId(asList);
		if (CollUtil.isNotEmpty(categoryBrandRelationEntities)) {
			List<Long> existCatalogId = categoryBrandRelationEntities.stream().map(CategoryBrandRelationEntity::getCatelogId).distinct().collect(Collectors.toList());
			asList = asList.stream().filter(item -> !existCatalogId.contains(item)).collect(Collectors.toList());
		}
		// 删除目录
		baseMapper.deleteBatchIds(asList);
	}

	@Override
	public Long[] findCatelogPath(Long catelogId) {
		List<Long> ids = new ArrayList<>();
		CategoryEntity byId = baseMapper.selectById(catelogId);
		while (!byId.getParentCid().equals(0L)) {
			ids.add(byId.getCatId());
			byId = baseMapper.selectById(byId.getParentCid());
		}
		ids.add(byId.getCatId());
		Collections.reverse(ids);
		return ids.toArray(new Long[0]);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	@CacheEvict(cacheNames = "PRODUCT", allEntries = true)
	public void updateDetails(CategoryEntity category) {
		baseMapper.updateById(category);
		if (StrUtil.isNotEmpty(category.getName())) {
			categoryBrandRelationService.updateCatalog(category.getCatId(), category.getName());
		}
	}

	@Cacheable(cacheNames = "PRODUCT", key = "'level1catalogJson'")
	@Override
	public List<CategoryEntity> getLevel1Category() {
		return this.lambdaQuery()
				.eq(CategoryEntity::getParentCid, 0)
				.list();
	}

	@Cacheable(cacheNames = "PRODUCT", key = "'catalogJson'")
	@Override
	public Map<String, List<Catelog2Vo>> getCatalogJson() {
		// 分布式锁，cas操作，防止高并发情况下，都去查数据库
		RLock lock = redissonClient.getLock("");
		try {
			// 加锁
			lock.lock();
			// 若缓存中有，直接返回
			Cache product = cacheManager.getCache("PRODUCT");
			String json = Objects.nonNull(product) ? product.get("catalogJson", String.class) : null;
			if (Objects.nonNull(json)) {
				return JSON.parseObject(json, new TypeReference<Map<String, List<Catelog2Vo>>>() {
				});
			}
			// 缓存中没有，从数据查询
			log.info("从数据库查询");
			List<CategoryEntity> allCategory = this.list();
			// 筛选出一级分类
			List<CategoryEntity> level1 = filter(allCategory, 0L);
			return level1.stream().collect(Collectors.toMap(l1 -> l1.getCatId().toString(), l1 -> {
				// 筛选出二级分类，封装成vo
				List<CategoryEntity> l2List = filter(allCategory, l1.getCatId());
				return l2List.stream().map(l2 -> {
					// 筛选出三级分类，封装成vo
					List<Catelog2Vo.Category3Vo> l3List = allCategory.stream().filter(item -> item.getParentCid().equals(l2.getCatId()))
							.map(item -> new Catelog2Vo.Category3Vo(item.getParentCid().toString(), item.getCatId().toString(), item.getName()))
							.collect(Collectors.toList());
					return new Catelog2Vo(l2.getParentCid().toString(), l3List, l2.getCatId().toString(), l2.getName());
				}).collect(Collectors.toList());
			}));
		} finally {
			lock.unlock();
		}
	}

	/**
	 * 过滤出指定父id的元素
	 *
	 * @param categoryEntities 需要过滤的集合
	 * @param parentCatId      父id
	 * @return 过滤后的集合
	 */
	private List<CategoryEntity> filter(List<CategoryEntity> categoryEntities, Long parentCatId) {
		return categoryEntities.stream().filter(item -> item.getParentCid().equals(parentCatId)).collect(Collectors.toList());
	}

	/**
	 * 获取指定节点的子树
	 *
	 * @param root 指定节点
	 * @param all  所有的节点
	 * @return 指定节点的子树
	 */
	private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all) {
		return all.stream().filter(item -> item.getParentCid().equals(root.getCatId()))
				.peek(item -> item.setChildren(getChildren(item, all)))
				.sorted(Comparator.comparingInt(item -> (item.getSort() == null ? 0 : item.getSort())))
				.collect(Collectors.toList());
	}

}